package com.zhanhong.opencvdemo.utils;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.zhanhong.opencvdemo.core.Core;


public final class SpUtils {

    public enum SpType {
        KEY_QUESTION_COUNT,
        KEY_SINGLE_CHOICE_QUESTION_ALL,
        KEY_RECOGNITION_CONFIG,
    }

    private static final SharedPreferences PREFERENCES = PreferenceManager.getDefaultSharedPreferences(Core.getApplicationContext());

    private static SharedPreferences getAppPreference() {
        return PREFERENCES;
    }

    public static void clear() {
        getAppPreference().edit().clear().apply();
    }

    public static void remove(Enum<SpType> key) {
        getAppPreference().edit().remove(key.name()).apply();
    }

    public static void save(Enum<SpType> key, Object value) {
        SharedPreferences.Editor edit = getAppPreference().edit();
        if (value instanceof Boolean) {
            edit.putBoolean(key.name(), (boolean) value);
        } else if (value instanceof Integer) {
            edit.putInt(key.name(), (int) value);
        } else if (value instanceof Long) {
            edit.putLong(key.name(), (long) value);
        } else if (value instanceof Float) {
            edit.putFloat(key.name(), (float) value);
        } else if (value instanceof String) {
            edit.putString(key.name(), (String) value);
        } else {
            throw new RuntimeException("Can't save this type of value");
        }
        edit.apply();
    }

    public static boolean readBoolean(Enum<SpType> key) {
        return getAppPreference().getBoolean(key.name(), false);
    }

    public static boolean readBoolean(Enum<SpType> key, Boolean defaultValue) {
        return getAppPreference().getBoolean(key.name(), defaultValue);
    }

    public static int readInt(Enum<SpType> key) {
        return getAppPreference().getInt(key.name(), 0);
    }

    public static long readLong(Enum<SpType> key) {
        return getAppPreference().getLong(key.name(), 0);
    }

    public static float readFloat(Enum<SpType> key) {
        return getAppPreference().getFloat(key.name(), 0F);
    }

    public static String readString(Enum<SpType> key) {
        return getAppPreference().getString(key.name(), "");
    }

}
